<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import config from '../../config.js';
import { useRouter, useRoute } from 'vue-router';

// 股票表单数据
const stock = ref({
  name: '',
  code: ''
});
// 加载状态
const loading = ref(false);
// 错误信息
const error = ref('');
// 成功信息
const success = ref('');
// 是否为编辑模式
const isEditMode = ref(false);
const router = useRouter();
const route = useRoute();
const stockId = route.params.id;

// 组件挂载时加载数据
onMounted(() => {
  if (stockId) {
    // 编辑模式，加载股票数据
    isEditMode.value = true;
    loadStockData(stockId);
  }
});

// 加载股票数据
const loadStockData = async (id) => {
  loading.value = true;
  error.value = '';

  try {
    const response = await axios.get(`${config.api.baseUrl}/api/stocks/${id}`);
    stock.value = response.data;
    console.log('股票数据加载成功:', stock.value);
  } catch (err) {
    error.value = '加载股票数据失败: ' + (err.response?.data?.error || err.message);
    console.error('加载股票数据失败:', err);
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  // 简单验证
  if (!stock.value.name.trim() || !stock.value.code.trim()) {
    error.value = '股票名称和代码不能为空';
    return;
  }

  loading.value = true;
  error.value = '';
  success.value = '';

  try {
    if (isEditMode.value) {
      // 编辑模式，调用更新接口
      await axios.put(`${config.api.baseUrl}/api/stocks/${stockId}`, stock.value);
      success.value = '股票信息更新成功';
    } else {
      // 新增模式，调用新增接口
      await axios.post(`${config.api.baseUrl}/api/stocks`, stock.value);
      success.value = '股票信息新增成功';
      // 重置表单
      stock.value = {
        name: '',
        code: ''
      };
    }
    console.log(isEditMode.value ? '股票更新成功' : '股票新增成功');

    // 3秒后跳转到列表页面
    setTimeout(() => {
      router.push('/stocks');
    }, 1500);
  } catch (err) {
    error.value = (isEditMode.value ? '更新' : '新增') + '股票失败: ' + (err.response?.data?.error || err.message);
    console.error((isEditMode.value ? '更新' : '新增') + '股票失败:', err);
  } finally {
    loading.value = false;
  }
};

// 取消操作
const cancel = () => {
  router.push('/stocks');
}

// 返回首页
const goToHome = () => {
  router.push('/');
};
</script>

<template>
  <div class="stock-form-container">
    <h1>{{ isEditMode ? '编辑股票' : '新增股票' }}</h1>

    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="success" class="success-message">{{ success }}</div>

    <form class="stock-form" @submit.prevent="submitForm">
      <div class="form-group">
        <label for="name">股票名称:</label>
        <input
          type="text"
          id="name"
          v-model="stock.name"
          placeholder="请输入股票名称"
          :disabled="loading"
        >
      </div>

      <div class="form-group">
        <label for="code">股票代码:</label>
        <input
          type="text"
          id="code"
          v-model="stock.code"
          placeholder="请输入股票代码"
          :disabled="loading"
        >
      </div>

      <div class="form-actions">
        <button type="submit" :disabled="loading">{{ isEditMode ? '更新' : '保存' }}</button>
        <button type="button" @click="cancel" :disabled="loading">取消</button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.stock-form-container {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.error-message {
  color: #e74c3c;
  padding: 10px;
  background-color: #fadbd8;
  border-radius: 4px;
  margin-bottom: 15px;
}

.success-message {
  color: #27ae60;
  padding: 10px;
  background-color: #d5f5e3;
  border-radius: 4px;
  margin-bottom: 15px;
}

.stock-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-group input:disabled {
  background-color: #f2f2f2;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.form-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.form-actions button[type="submit"] {
  background-color: #42b983;
  color: white;
}

.form-actions button[type="button"] {
  background-color: #95a5a6;
  color: white;
}

.form-actions button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}
</style>